package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisMessageConstant;
import com.atguigu.pojo.Member;
import com.atguigu.service.MemberSrevice;
import com.atguigu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/Login")
public class LoginController {

    @Reference
    MemberSrevice memberSrevice;

    @Autowired
    JedisPool jedisPool;

    @PostMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        String validateCode = (String)map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String reidsCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if (reidsCode == null || !validateCode.equals(reidsCode)){
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }

        Member member = memberSrevice.findByTelephone(telephone);
        if (member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberSrevice.seve(member);
        }

        Cookie cookie = new Cookie("telrphone_login",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);

        return new Result(true,MessageConstant.LOGIN_SUCCESS);
    }
}
